package net.ojbk.timeSpace.test.web.interceptors;

import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import net.ojbk.timeSpace.test.beans.TimeAxis;
import net.ojbk.timeSpace.test.service.IAxisService;

public class ServletContextInterceptor implements HandlerInterceptor {

	@Autowired
	@Qualifier("axisService")
	private IAxisService axisService;
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 用户访问次数统计 与 servletContext初始化
		ServletContext sc = request.getServletContext();
		// 检查 sc 的 tokenMap
		HashMap<String, HttpSession> tokenMap = (HashMap<String, HttpSession>) sc.getAttribute("tokenMap");
		if (tokenMap == null) {
			tokenMap = new HashMap<String, HttpSession>();
			sc.setAttribute("tokenMap", tokenMap);
		} 
		// 检查timeAxisMap
		HashMap<Integer, TimeAxis> timeAxisMap = (HashMap<Integer, TimeAxis>) sc.getAttribute("timeAxisMap");
		if (timeAxisMap == null) {
			List<TimeAxis> timeAxisList = axisService.getAllAxis();
			// List转Map
			// CSDN Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
			timeAxisMap = (HashMap<Integer, TimeAxis>) timeAxisList.stream().collect(Collectors.toMap(TimeAxis::getAxisId, Function.identity(),(k1,k2)->k1));
			// 成功
			// System.out.println(timeAxisMap);
			
			sc.setAttribute("timeAxisMap", timeAxisMap);
		}
		
		
		// ---------------------------------------------------------------------
		// 统计数量
		int peopleSum = 1;
		if (sc.getAttribute("peopleSum") != null)
			peopleSum += (int)(sc.getAttribute("peopleSum"));
		sc.setAttribute("peopleSum", peopleSum);
		System.out.println("本次启动访问总数量：" + peopleSum);
		return true;
		
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
